# -*- coding:utf-8 -*-

import json

from domain import HTTP, SvrType, Result

_SVR_TYPE = 'svr_type'
_KEY_QUERY = 'queryStringParameters'


def find_args(*args):
    return args[0] if len(args) else {}


def create_hwcfs_request(params: dict = {}):
    return {
        'queryStringParameters': params
    }


def set_hwcfs_response(result: Result = None, **kwargs):
    return {
        "statusCode": HTTP.STATUS_CODE.OK if result and result.result == Result.SUCCESS else HTTP.STATUS_CODE.INTERNAL_SERVER_ERROR,
        "isBase64Encoded": kwargs.get('isBase64Encoded', False),
        "body": json.dumps(result.format()) if result else {},
        "headers": {
            "Content-Type": kwargs.get('content_type', 'application/json')
        }
    }


def convert(func):
    def wrapper(*args, **kw):
        params = {}

        req = find_args(*args)
        svr_type = req.get(_SVR_TYPE, SvrType.FASTAPI)
        if svr_type == SvrType.LESS:
            params = req.get(_KEY_QUERY, {})

        elif svr_type == SvrType.FASTAPI:
            params = req.query_params.__dict__['_dict']

        else:
            params = find_args(*args)

        return func(**params)

    return wrapper


def serverless(func):
    def wrapper(*args, **kw):
        params = find_args(*args)
        params[_SVR_TYPE] = SvrType.LESS

        return func(*args, **kw)

    return wrapper
